
/**
 * @author oven:
 * @version 创建时间：2013-4-15 上午8:58:57
 * 
 */
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
public class CutImage {
 private BufferedImage img;
 private BufferedImage child;
 public CutImage(){
  
 }
 
 public CutImage(BufferedImage im){
  img=im;
 }
 
 public CutImage(Image im){
  img=(BufferedImage)im;
 }
 public void setImg(BufferedImage img) {
  this.img = img;
 }
 public BufferedImage getChildImage(int x,int y,int width,int height) {
  int cw=width;
  int ch=height;
  int pw=img.getWidth();
  int ph=img.getHeight();
  if(pw<x+width){
   System.out.println("给出的参数超出原图片的范围！程序会自动减小宽度或高度");
   cw=pw-x;
  }
  if(ph<y+height){
   System.out.println("给出的参数超出原图片的范围！程序会自动减小宽度或高度");
   ch=ph-y;
  }
  child=new BufferedImage(cw,ch,BufferedImage.TYPE_INT_ARGB );
  for(int i=0;i<ch;i++){
   for(int j=0;j<cw;j++){
    child.setRGB(j, i, img.getRGB(x+j, y+i));
   }
  }
  return child;
 }
 
 
 public static void main(String[] args) throws IOException {
	 cutImageToHalf("D:\\uis\\hori\\","D:\\newuis\\","_cut_",true);
	 cutImageToHalf("D:\\uis\\verti\\","D:\\newuis\\","_cut_",false);
 }
 
 public static void cutImageToHalf(String resPath,String desPath,String endFix,boolean hori) throws IOException{
	 File path = new File(resPath);
	 if(path.isDirectory()){
		 String files[] = path.list();
		 for(int i=0;i<files.length;i++){
			 String fileName = files[i];
			 String fileType = fileName.substring(fileName.indexOf("."));
			 fileName = fileName.substring(0,fileName.indexOf(".")) ;
			 String filePath = resPath+fileName+fileType;
			 BufferedImage[] pieces = cutImageToHalf(filePath,hori);
			 for(int j=0;j<pieces.length;j++){
				 File newFile = new File(desPath+fileName+endFix+j+fileType);
				 ImageIO.write(pieces[j], "png", newFile);
			 }
		 }
	 }
 }
 
 public static BufferedImage[] cutImageToHalf(String filePath,boolean hori) throws IOException{
	 System.out.println("加载图片:"+filePath);
	 BufferedImage bi = ImageIO.read(new File(filePath)); 
	 int width = bi.getWidth();
	 int height = bi.getHeight();
	 CutImage cutImage = new CutImage();
	 cutImage.setImg(bi);
	 if(hori){
		 BufferedImage imagePiece1 = cutImage.getChildImage(0, 0, width/2, height);
		 BufferedImage imagePiece2 = cutImage.getChildImage(width/2, 0, width/2, height);
		 BufferedImage[] result = new BufferedImage[2];
		 result[0] = imagePiece1;
		 result[1] = imagePiece2;
		 return result;
	 }else{
		 BufferedImage imagePiece1 = cutImage.getChildImage(0, 0, width, height/2);
		 BufferedImage imagePiece2 = cutImage.getChildImage(0, height/2, width, height/2);
		 BufferedImage[] result = new BufferedImage[2];
		 result[0] = imagePiece1;
		 result[1] = imagePiece2;
		 return result;
	 }
 }
}

